package com.hd.trans.ui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.ui.adapter.LanguagePackageAdapter;
import com.hd.trans.ui.base.BaseActivity;
import com.hd.trans.utils.OfflineConstant;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;
import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hms.mlsdk.common.MLApplication;
import com.huawei.hms.mlsdk.model.download.MLLocalModelManager;
import com.huawei.hms.mlsdk.model.download.MLModelDownloadListener;
import com.huawei.hms.mlsdk.model.download.MLModelDownloadStrategy;
import com.huawei.hms.mlsdk.model.download.MLRemoteModel;
import com.huawei.hms.mlsdk.translate.local.MLLocalTranslatorModel;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Set;

public class OfflineHomeActivity extends BaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_offline_home;
    }



    private RecyclerView recyclerView;
    private LanguagePackageAdapter adapter;
    private MLLocalModelManager manager;

    private static ArrayList<String> downloadedModelList = new ArrayList<>();
    private static HashMap<String, String> downloadMap = new HashMap<>();

    public static void open(Context context) {
        Intent intent = new Intent(context, OfflineHomeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);
        TranslationInterior.getTrackerListener().view("离线翻译包页面");
        setApiKey();
        initViews();
        initData();
        setListener();
    }

    private void setApiKey(){
        AGConnectServicesConfig config = AGConnectServicesConfig.fromContext(this);
        MLApplication.getInstance().setApiKey(config.getString("client/api_key"));
    }

    private void initViews() {
        ((TextView)findViewById(R.id.tv_title)).setText(getResources().getString(R.string.offline_translate));
        recyclerView = findViewById(R.id.recycler_view);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new LanguagePackageAdapter(OfflineConstant.DOWNLOAD_LANG_LIST,downloadedModelList, downloadMap);
        //adapter.setAnimationEnable(true);
        //adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                if(XClickUtil.isFastDoubleClick(view,XClickUtil.INTERVAL_MILLIS)){
                    return;
                }
                if(view.getId() == R.id.tv_download){
                    TextView tvDownload = (TextView) view;
                    String languageCode = OfflineConstant.DOWNLOAD_LANG_LIST.get(position).getTranslateCode();

                    if(tvDownload.getText().toString().equals("下载")){
                        TranslationInterior.getTrackerListener().click(TrackerForTrans.OFFLINE_TRANS,TrackerForTrans.DOWNLOAD);
                        checkNetworkAndDoNext(languageCode,tvDownload,position);
                    }else if(tvDownload.getText().toString().equals("删除")){
                        //删除
                        TranslationInterior.getTrackerListener().click(TrackerForTrans.OFFLINE_TRANS,TrackerForTrans.DELETE);
                        deleteModel(languageCode, position);
                    }

                }else if(view.getId() == R.id.rl_parent){
                    //
                }
            }
        });
    }

    private void checkNetworkAndDoNext(String languageCode,final TextView tvDownload,int position) {
        int net = OfflineConstant.checkNetwork(OfflineHomeActivity.this);
        switch (net) {
            case OfflineConstant.NETWORK_WIFI:
                downloadModel(languageCode,tvDownload,position);
                break;
            case OfflineConstant.NETWORK_MOBILE:
                new AlertDialog.Builder(OfflineHomeActivity.this).setTitle(R.string.prompt)
                        .setMessage(R.string.no_wifi_prompt)
                        .setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                downloadModel(languageCode,tvDownload, position);
                            }
                        }).setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create().show();
                break;
            default:
                new AlertDialog.Builder(OfflineHomeActivity.this).setTitle(R.string.prompt)
                        .setMessage(R.string.no_network_prompt)
                        .setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create().show();
        }
    }

    private void initData() {
        manager = MLLocalModelManager.getInstance();
        manager.getModels(MLLocalTranslatorModel.class).addOnSuccessListener(new OnSuccessListener<Set<MLLocalTranslatorModel>>() {
            @Override
            public void onSuccess(Set<MLLocalTranslatorModel> mlLocalTranslatorModels) {

                downloadedModelList.clear();
                for (MLRemoteModel m : mlLocalTranslatorModels) {
                    String modelName = m.getModelName().substring(m.getModelName().indexOf("_") + 1);
                    if (!downloadedModelList.contains(modelName)) {
                        downloadedModelList.add(modelName);
                    }
                }

                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
        });

        /*MLTranslateLanguage.getLocalAllLanguages().addOnSuccessListener(
                new OnSuccessListener<Set<String>>() {
                    @Override
                    public void onSuccess(Set<String> result) {
                        // 成功获取本地离线翻译支持的语种。
                        Log.e("liaoyucheng",result.toString());
                    }
                });*/
    }


    private void setListener(){
        findViewById(R.id.iv_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 下载语种包
     */
    private void downloadModel(final String languageCode,final TextView tvDownload,int position) {

        downloadMap.put(languageCode, getString(R.string.waitting));
        if (adapter != null) {
            mXHandler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
        }

        MLLocalTranslatorModel model = new MLLocalTranslatorModel.Factory(languageCode).create();

        MLModelDownloadListener modelDownloadListener = new MLModelDownloadListener() {
            @Override
            public void onProcess(long alreadyDownLength, long totalLength) {
                showProcess(languageCode, alreadyDownLength, totalLength,position);
            }
        };
        MLModelDownloadStrategy request = new MLModelDownloadStrategy.Factory()
                .create();

        manager.downloadModel(model, request, modelDownloadListener).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                downloadedModelList.add(languageCode);
                downloadMap.remove(languageCode);
                if (adapter != null) {
                    mXHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
                OfflineConstant.updateModel();
                ToastUtils.showNormal(R.string.download_success);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                downloadMap.remove(languageCode);
                if (adapter != null) {
                    mXHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
                ToastUtils.showNormal(R.string.download_failure);
            }
        });
    }

    private void showProcess(String languageCode, long alreadyDownLength, long totalLength,int position) {
        /*double downDone = alreadyDownLength * 1.0 / OfflineConstant.M;
        double downTotal = totalLength * 1.0 / OfflineConstant.M;
        String downD = String.format(Locale.ROOT,"%.2f", downDone);
        String downT = String.format(Locale.ROOT,"%.2f", downTotal);

        String text = downD + "M" + "/" + downT + "M";*/
        String text = String.format(Locale.ROOT,"下载%2d%s", alreadyDownLength*100/totalLength,"%");
        downloadMap.put(languageCode, text);
        if (adapter != null) {
            mXHandler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }

    private void deleteModel(final String languageCode,int position) {
        MLLocalTranslatorModel model = new MLLocalTranslatorModel.Factory(languageCode).create();
        manager.deleteModel(model).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                downloadedModelList.remove(languageCode);
                adapter.notifyDataSetChanged();
                ToastUtils.showNormal(R.string.delete_success);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                adapter.notifyDataSetChanged();
                ToastUtils.showNormal(R.string.delete_failure);
            }
        });

    }
}
